<?php

class Log
{

  public static function dbg($str, $newline = 1)
  {
    if ($GLOBALS["DBG_FILE"])
      {
	Log::dbg_to_file($GLOBALS["DBG_FILE"], $str, $newline);
      }
    else 
      {
      
      }
  }

  public static function profile_start()
  {    
    if (!isset($GLOBALS["PROFILE_DIR"]))
      {
	return ;
      }
    $GLOBALS["PROFILE_CACHE"] = array();
    $GLOBALS["PROFILE_COUNT"] = 0;
    if (! file_exists($GLOBALS["PROFILE_DIR"]))
      {
	mkdir($GLOBALS["PROFILE_DIR"]);
      }
    foreach (glob($GLOBALS["PROFILE_DIR"]."*.log") as $f) 
      {
	unlink($f);   
      }
  }

  public static function profile_next()
  {
    if (!isset($GLOBALS["PROFILE_DIR"]))
      {
	return ;
      }
    $GLOBALS["PROFILE_COUNT"]++;
  }
  
  public static function profile($file, $str, $depth)
  {
    if (!isset($GLOBALS["PROFILE_DIR"]))
      {
	return ;
      }

    if (array_key_exists("PROFILE_COUNT", $GLOBALS) == false)
      {
	Log::profile_start();
      }
    
    $f = $GLOBALS["PROFILE_DIR"].$GLOBALS["PROFILE_COUNT"].".log";
    $bt = debug_backtrace(false);
    $c = 0;
    while ($c < $depth && $t = array_shift($bt))
      {
	if (array_key_exists("file", $t))
	  {
	    if (strpos($t["file"], "/test"))
	      {
		$c++;
	      }
	  }
	else
	  {
	    
	  }
      }
    
    if ($t)
      {
	if (!array_key_exists($f, $GLOBALS["PROFILE_CACHE"]))
	  {
	    $GLOBALS["PROFILE_CACHE"][$t["file"]] = file($t["file"]);
	  }
	$s = preg_replace("|.*/|", "", $t["file"]);
	$c = preg_replace("|.*/|", "", $file);
	Log::dbg_to_file($f, "\n\n$str");// - profile from file $c");
	Log::dbg_to_file($f, "\t" . "File {$s} at line {$t["line"]}");
	Log::dbg_to_file($f, "\t" . trim($GLOBALS["PROFILE_CACHE"][$t["file"]][$t["line"]-1]));
      }
    else
      {
	Log::dbg_to_file($f, "Could not find line");// - profile from file $c");	    
	Log::dbg_to_file($f, $bt);// - profile from file $c");	    
      }
    }

  public static function dbg_to_file($file, $str, $newline = 1)
  {
    $out = "";
    if (isset($str) == false)
      {
	$out = "[not set]";
      }
    if (is_array($str))
      {
	$out = array_to_string($str);
      }
    if (is_object($str))
      {
	$out = array_to_string($str);
      }
    if (! $out)
      {
	$out = $str;
      }

    $fp = fopen($file, 'a');
    fwrite($fp, $out . str_repeat("\n", $newline));
    fclose($fp); 
    unset($fp);
  }
}

function array_to_string($array, $depth = 1) 
{ 
  $str = "";
  if ($depth == 1)
    {
      $str = "array(";
    }
  foreach($array as $name => $value ) 
  { 
    $str .= "\n".str_repeat(" ", $depth *4 ) . "'$name' => ";
    if( is_array( $value ) ) 
    { 
      if ($depth<10)
	$str .= array_to_string($value, $depth+1); 
    } 
    else if( is_object( $value ) ) 
    { 
      if ($depth<10)
	$str .= array_to_string($value, $depth+1); 
    } 
    else 
    { 
      $str .= "'$value',";
    } 
  } 
  $str .= ")";
  if ($depth == 1)
    {
      $str .= ";";
    }
  return $str;
} 
?>